import React, { useEffect } from 'react';
import { BrowserRouter } from 'react-router-dom';
import { Provider, useDispatch } from 'react-redux';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import Router from './router';
import { store } from './store';
import { setToken } from './store/slices/auth';
import { setMenus } from './store/slices/menu';
import { setMerchantList, setCurrentEntity } from './store/slices/merchant';
import { useTitle } from './hooks/useTitle';
import TitleManager from './components/TitleManager';
import './App.less';

// 初始化组件，用于加载本地存储的状态
const AppInitializer: React.FC = () => {
  const dispatch = useDispatch();
  
  // 设置页面标题
  useTitle();

  useEffect(() => {
    // 从本地存储加载token和菜单数据
    const token = localStorage.getItem('token');
    const menuData = localStorage.getItem('menuData');
    const merchantIdentity = localStorage.getItem('merchantIdentity');
    const currentMerchantEntity = localStorage.getItem('currentMerchantEntity');

    if (token) {
      dispatch(setToken(token));
    }

    if (menuData) {
      try {
        const menus = JSON.parse(menuData);
        dispatch(setMenus(menus));
      } catch (error) {
        console.error('Failed to parse menu data', error);
      }
    }

    // 加载商家身份数据
    if (merchantIdentity) {
      try {
        const identityData = JSON.parse(merchantIdentity);
        if (identityData && identityData.list) {
          dispatch(setMerchantList(identityData.list));
        }
        if (identityData && identityData.current_entity) {
          dispatch(setCurrentEntity(identityData.current_entity));
        }
      } catch (error) {
        console.error('Failed to parse merchant identity data', error);
      }
    }

    // 加载当前选中的商家实体
    if (currentMerchantEntity) {
      try {
        const entity = JSON.parse(currentMerchantEntity);
        dispatch(setCurrentEntity(entity));
      } catch (error) {
        console.error('Failed to parse current merchant entity', error);
      }
    }
  }, [dispatch]);

  return <Router />;
};

const App: React.FC = () => {
  return (
    <Provider store={store}>
      <ConfigProvider locale={zhCN}>
        <BrowserRouter>
          <TitleManager>
            <AppInitializer />
          </TitleManager>
        </BrowserRouter>
      </ConfigProvider>
    </Provider>
  );
};

export default App;